package com.qk.management.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.constant.ClueStatusConstants;
import com.qk.common.constant.ClueTrackRecordTypeConstants;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.doman.clue.ClueDO;
import com.qk.doman.clue.CluePoolDO;
import com.qk.dto.clue.*;
import com.qk.entity.Business;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.util.CurrentUserContextHolders;
import com.qk.entity.Clue;
import com.qk.entity.ClueTrackRecord;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.mapper.ClueTrackRecordMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.ClueService;
import com.qk.vo.clue.ClueVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author 16778
 * @date 2025/10/13 16:55
 * @description
 */
@Slf4j
@Service
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;

    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private ClueMapper clueMapper;

    private PageResult<ClueDO> pageListMP(ClueQueryDTO dto){
        Page pageParam = new Page(dto.getPage(),dto.getPageSize());
        Page<ClueDO> res =this.baseMapper.selectByPageMP(pageParam,dto);
        return PageResult.<ClueDO>builder()
                .total(res.getTotal())
                .rows(res.getRecords())
                .build();

    }

    @Override
    public void addClue(ClueDTO dto) {
        if(ObjectUtil.isEmpty(dto.getPhone())||ObjectUtil.isEmpty(dto.getChannel())){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        clue.setCreateTime(LocalDateTime.now());
        clue.setUpdateTime(LocalDateTime.now());
        clue.setStatus(ClueStatusConstants.WAIT_ALLOCATION);
        this.baseMapper.insert(clue);
    }

    @Override
    public PageResult<ClueDO> pageList(ClueQueryDTO dto) {
//        PageHelper.startPage(dto.getPage(),dto.getPageSize());
//        Page<ClueDO> page =(Page<ClueDO>) this.baseMapper.selectByPage(dto);
//        return PageResult.<ClueDO>builder()
//                .total(page.getTotal())
//                .rows(page.getResult())
//                .build();
        return pageListMP(dto);
    }

    @Override
    public ClueVO selectWithRecords(Integer id) {
//        Clue clue = this.baseMapper.selectById(id);
//        Integer userId = clue.getUserId();
//        String assignName = userMapper.selectById(userId).getName();
//        List<ClueTrackRecord> clueTrackRecords = clueTrackRecordMapper.selectList(Wrappers.lambdaQuery(ClueTrackRecord.class)
//                .in(ClueTrackRecord::getClueId, id)
//        );
//        ClueVO clueVO = BeanUtil.copyProperties(clue, ClueVO.class);
//        clueVO.setAssignName(assignName);
//        List<User> users = userMapper.findALl();
//        Map<Integer,String> userMap = new HashMap<>();
//        for (User user : users) {
//            userMap.put(user.getId(),user.getName());x
//        }
//        List<ClueTrackRecordVO> clueTrackRecordVOS = clueTrackRecords.stream().map(clueTrackRecord -> {
//            ClueTrackRecordVO clueTrackRecordVO = BeanUtil.copyProperties(clueTrackRecord, ClueTrackRecordVO.class);
//            return clueTrackRecordVO;
//        }).toList();
//        for (ClueTrackRecordVO clueTrackRecord : clueTrackRecordVOS) {
//            clueTrackRecord.setAssignName(userMap.get(clueTrackRecord.getUserId()));
//        }
//        clueVO.setTrackRecords(clueTrackRecordVOS);
        ClueVO clueVO = this.baseMapper.selectWithRecordsByClueId(id);
        return clueVO;
    }


    @Override
    @Transactional
    public void updateClueTrackRecord(UpdateClueDTO dto) {
        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        clue.setUpdateTime(LocalDateTime.now());
        if(dto.getStatus()==ClueStatusConstants.WAIT_FOLLOW_UP){
            clue.setStatus(ClueStatusConstants.FOLLOW_UP);
        }
        this.baseMapper.updateById(clue);

        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(dto, ClueTrackRecord.class);
        clueTrackRecord.setId(null);
        clueTrackRecord.setClueId(dto.getId());
        clueTrackRecord.setUserId(CurrentUserContextHolders.getCurrentUserId());
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        clueTrackRecord.setType(ClueTrackRecordTypeConstants.NORMAL_FOLLOW_UP);
        clueTrackRecordMapper.insert(clueTrackRecord);
    }

    @Override
    @Transactional
    public void updateFalseClue(Integer id, MarkFalseClueDTO dto) {
        Clue clue = new Clue();
        clue.setStatus(ClueStatusConstants.FAKE_CLUE);
        clue.setUpdateTime(LocalDateTime.now());
        clue.setId(id);
        this.baseMapper.updateById(clue);

        ClueTrackRecord clueTrackRecord = new ClueTrackRecord();
        clueTrackRecord.setClueId(id);
        clueTrackRecord.setUserId(CurrentUserContextHolders.getCurrentUserId());
        clueTrackRecord.setType(ClueTrackRecordTypeConstants.FALSE_CLUE);
        clueTrackRecord.setRecord(dto.getRemark());
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        clueTrackRecord.setFalseReason(dto.getReason());
        clueTrackRecordMapper.insert(clueTrackRecord);
    }

    @Override
    public void convertTOBusiness(Integer id) {
        Clue clue = this.baseMapper.selectById(id);
        clue.setStatus(ClueStatusConstants.CONVERT_TO_BUSINESS);
        clue.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(clue);


        Business business = BeanUtil.copyProperties(clue, Business.class);
        business.setId(null);
        business.setUserId(null);
        business.setNextTime(null);
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        business.setClueId(id);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());

        businessMapper.insert(business);
    }

    @Override
    public PageResult<CluePoolDO> pool(CluePoolDTO dto) {
        dto.setStatus(ClueStatusConstants.FAKE_CLUE);
        Page pageParam = new Page(dto.getPage(),dto.getPageSize());
        Page<CluePoolDO> res =clueMapper.pool(pageParam,dto);
        return PageResult.<CluePoolDO>builder()
                .total(res.getTotal())
                .rows(res.getRecords())
                .build();
    }
}
